/*
 * @Author: xiaosihan 
 * @Date: 2024-07-14 13:23:18 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-17 17:33:06
 */


import partsApi from "@api/partsApi";
import utilsApi from "@api/utilsApi";
import utils from "@utils";
import { find, get } from "lodash";
import { autorun } from "mobx";
import numeral from "numeral";
import { ReactNode, useEffect, useRef, useState } from "react";
import PCHeader from "../PCHeader/PCHeader";
import thumbRenderer from "./thumbRenderer";
import styles from "./updataModel.module.less";
import uploadIcon1PNG from "./uploadIcon1.png";
import uploadIcon2PNG from "./uploadIcon2.png";
import UploadProgressModal from "./UploadProgressModal/UploadProgressModal";
import uploadProgressModalStore from "./UploadProgressModal/uploadProgressModalStore";
import hashHistory from "@hashHistory";

// import formatConvert from "./formatConvert/formatConvert";

interface Iprops {
    children?: ReactNode
}

// 上传模型获取报价
export default function UpdataModel() {

    const dom = useRef<HTMLDivElement | null>(null);
    const [data, setData] = useState({});

    useEffect(() => {

    }, []);

    useEffect(() => autorun(() => {

    }), []);

    //上传3d模型
    const updataMadel = async (parame_file?: File) => {
        // let file = parame_file || await utils.selectFile(".STEP,.STP,.SLDPRT,.STL,.SAT,.3DXML,.PRT,.ITP,.CATPART,.X_T,.PTC,.X_B,STL,.STP,.PRT,.SLP,.SLDPRT,.STEP,.OBJ,.IGES,.XT,.X_T,.DXF,.SLDASM,.IPT,.GLTF,.GLB,.X_B,.PAR,.GBR,.BRD,.DWFX,.FBX,.zip");
        let file = parame_file || await utils.selectFile(".fbx,.obj,.stl,.gltf,.glb,.usdz.zip");

        if (file) {
            // const gltfFile = await utils.to_gltf([file]);
            uploadProgressModalStore.setOpen(true);
            // uploadProgressModalStore.setFormmatConrt(true);
            uploadProgressModalStore.setFileName(file.name);
            await new Promise(resolve => setTimeout(resolve, 100));
            // 格式转换
            // if (file) {
            //     const glbFile = await formatConvert(file, "glb");
            //     file = glbFile;
            // }
            // uploadProgressModalStore.setFormmatConrt(false);

            // 上传文件, 上传缩率图, 获取类型id 同时进行
            const [modelUrl, thumbUrl, typeId] = await Promise.all([
                new Promise<string>(async (resolve, reject) => {
                    const url = await utilsApi.uploadOss(file as File, (progress) => {
                        uploadProgressModalStore.setProgress(progress);
                    });
                    uploadProgressModalStore.setProgress(1);
                    resolve(url);
                }),
                new Promise<string>(async (resolve, reject) => {
                    const thumbFile = await thumbRenderer.get_thumb_file(file as File);
                    const thumbUrl = await utilsApi.uploadOss(thumbFile);
                    resolve(thumbUrl);
                }),
                new Promise<string>(async (resolve, reject) => {
                    const modalTypeResult = await partsApi.getModelType();
                    const modalTypeList = get(modalTypeResult, ["data", "data"]);
                    const typeId = get(find(modalTypeList, d => d.name === "3D模型"), ["id"]);
                    resolve(typeId);
                })
            ]);

            const addResult = await partsApi.add(typeId, (file as File).name, modelUrl, thumbUrl, numeral((file as File).size).format('0.0b'), "");
            const modelId = get(addResult, ["data", "id"]);
            uploadProgressModalStore.setModelId(modelId);

            while (uploadProgressModalStore.open) {
                await new Promise(resolve => requestAnimationFrame(resolve));
            }

            hashHistory.push("/partsLibrary");

        }
    }

    //上传cad 图纸
    const updataCad = async () => {
        const file = await utils.selectFile(".DWS,.DWF,.DWG,.DXF,.PDF");
        if (file) {
            uploadProgressModalStore.setOpen(true);
            uploadProgressModalStore.setFileName(file.name);

            // 上传文件, 获取类型id 同时进行
            const [url, typeId] = await Promise.all([
                new Promise<string>(async (resolve, reject) => {
                    const url = await utilsApi.uploadOss(file, (progress) => {
                        uploadProgressModalStore.setProgress(progress);
                    });
                    uploadProgressModalStore.setProgress(1);
                    resolve(url);
                }),
                new Promise<string>(async (resolve, reject) => {
                    const modalTypeResult = await partsApi.getModelType();
                    const modalTypeList = get(modalTypeResult, ["data", "data"]);
                    const typeId = get(find(modalTypeList, d => d.name === "工程图纸"), ["id"]);
                    resolve(typeId);
                })
            ]);

            const addResult = await partsApi.add(typeId, file.name, url, "", numeral(file.size).format('0.0b'), "");
            const modelId = get(addResult, ["data", "id"]);
            uploadProgressModalStore.setModelId(modelId);

            while (uploadProgressModalStore.open) {
                await new Promise(resolve => setTimeout(resolve, 200));
            }
            hashHistory.push("/partsLibrary");

        }
    }


    return (
        <div className={styles.updataModel} >
            <PCHeader />
            <div className={styles.big_title} >零件和规格</div>

            <div className={styles.box1} >

                <div
                    className={styles.centerCenter}
                    onDragOver={e => {
                        e.preventDefault();
                    }}
                    onDrop={e => {
                        e.preventDefault();
                        const file = get(e, ["dataTransfer", "files", 0]);
                        if (file) {
                            updataMadel(file);
                        }
                    }}
                >

                    <div className={styles.sub_title} >上传文件</div>
                    <div className={styles.describe} >
                        我们接受CAD文件、PDF图纸和BOM电子表格
                    </div>

                    <div className={styles.upload} onClick={() => updataMadel()}>
                        <img src={uploadIcon1PNG} className={styles.icon} alt="" />
                        <div className={styles.category} >3D模型</div>
                        <div className={styles.text} >
                            将文件直接拖进该区域或者点击颜色区域上传 <br />
                            如果是多个文件,请放到一个zip包里面
                        </div>
                        <div className={styles.forrmat} >
                            {
                                ["obj", "|", "3mf", "|", "3dm", "|", "dwfx", "|", "dfx", "|", "fbx", "|", "gltf", "|", "glb", "|", "Gcode", "|", "stp", "|", "step", "|", "igs", "|", "iges", "|", "brep", "|", "Solidworks(sldasm、sldprt)", "|", "Parasolid(x_t、x_b)", "|", "UG NX(prt)", "|", "ProE/Creo(prt、asm)", "|", "Inventor (ipt、iam)", "|", "3dxm", "|", "cgr", "|", "SolidEdge (par、psm、asm)", "|", "CATPart"].map((format, i) => {
                                    return (
                                        <span key={i} className={styles.format_item}  >{format}</span>
                                    );
                                })
                            }
                        </div>
                    </div>

                    <div className={styles.upload} onClick={() => updataCad()} >
                        <img src={uploadIcon2PNG} className={styles.icon} alt="" />
                        <div className={styles.category} >工程图纸</div>
                        <div className={styles.text} >将文件直接拖进该区域或者点击颜色区域上传</div>
                        <div className={styles.forrmat} >
                            {
                                ["dwg", "|", "svg", "|", "dxf", "|", "pdf", "|", "md", "|", "word", "|", "excel", "|", "png", "|", "gif", "|", "bmp", "|", "jpg"].map((format, i) => {
                                    return (
                                        <span key={i} className={styles.format_item}  >{format}</span>
                                    );
                                })
                            }
                        </div>
                    </div>

                    <div className={styles.note} >
                        上传您的零件，以获取制造供应商的快速报价。
                    </div>
                </div>

            </div>

            <div
                className={styles.thumb}
                ref={dom => thumbRenderer.setContainer(dom)}
            ></div>

            {/* 上传进度弹窗 */}
            <UploadProgressModal />

        </div>
    );

}